package com.gexiaobao.pigeon.ui.fragment.mine.training

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.fragment.app.Fragment
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.TrainingBaseInfoBean
import com.gexiaobao.pigeon.app.model.bean.TrainingResultResponse
import com.gexiaobao.pigeon.app.util.WebSocketUtils
import com.gexiaobao.pigeon.app.util.WxShareUtils
import com.gexiaobao.pigeon.databinding.FragmentTrainingDetailBinding
import com.gexiaobao.pigeon.ui.adapter.MyPagerAdapter
import com.gexiaobao.pigeon.viewmodel.MyTrainingViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 17:54
 * @Describe    : 训放详情
 */
class FragmentTrainingDetail : BaseFragment<MyTrainingViewModel, FragmentTrainingDetailBinding>() {
    private var result: ArrayList<TrainingResultResponse.ResultList> = arrayListOf()
    private var trainingStatus: Int = -1
    private var trainingType: Int = -1
    private var intentType = -1//标记是在列表跳转进入还是 在添加跳转进入
    private var mId = -1
    private lateinit var webSocketUtils: WebSocketUtils

    private var handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.obj != null) {
                val data = msg.obj as ArrayList<TrainingResultResponse.ResultList>?
                if (!data.isNullOrEmpty()) {
                    eventViewModel.trainingResult.value = data
                }
                val bundle = msg.data
                val mLiberateTotal = bundle.getInt("liberateTotal")
                val mHomingTotal = bundle.getInt("homingTotal")
                eventViewModel.trainingBaseInfoResult.value = TrainingBaseInfoBean(
                    liberateTotal = mLiberateTotal, homingTotal =
                    mHomingTotal
                )
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.toolbar.initClose("训放详情") {
            if (intentType == 1) {
                nav().navigateUp()
            } else {
                nav().popBackStack(R.id.fragment_add_training, true)
            }
        }
        /** 1：我的训放列表进入； 2：添加训放成功后进入 */
        intentType = arguments?.getInt("type")!!
        mId = arguments?.getInt("id")!!
        trainingType = arguments?.getInt("trainingType")!! //2：普通训放。1：单只训放
        trainingStatus = arguments?.getInt("trainingStatus")!!
        initViewPager(mId)
        openWebSocket()
    }

    override fun onResume() {
        super.onResume()
        webSocketUtils.reConnect()
    }

    private fun openWebSocket() {
        val url = Constant.SOCKET_URL_BASE + "/u/v1/ws/createWebSocket?connType=3&trainingId=$mId&platform=android"
        webSocketUtils = WebSocketUtils(
            url,
            object : WebSocketListener() {
                override fun onOpen(webSocket: WebSocket, response: Response) {
                    super.onOpen(webSocket, response)
                    LogUtils.debugInfo("========================onOpen")
                }

                override fun onMessage(webSocket: WebSocket, text: String) {
                    super.onMessage(webSocket, text)
                    LogUtils.debugInfo("===================onMessage1-->text:$text")
                    if (text.isNotEmpty()) {
                        val liberateTotal = JSONObject(text).getInt("liberateTotal")
                        val homingTotal = JSONObject(text).getInt("homingTotal")
                        val list = JSONObject(text).getJSONArray("list")
                        val gson = Gson()
                        val type = object :
                            TypeToken<ArrayList<TrainingResultResponse.ResultList>>() {}.type
                        val result: ArrayList<TrainingResultResponse.ResultList> =
                            gson.fromJson(list.toString(), type)
                        val message = Message()
                        message.obj = result
                        val bundle = Bundle()
                        bundle.putInt("liberateTotal", liberateTotal)
                        bundle.putInt("homingTotal", homingTotal)
                        message.data = bundle
                        handler.sendMessage(message)
                    }
                }

                override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                    super.onMessage(webSocket, bytes)
                    LogUtils.debugInfo("========================onMessage2-->bytes:$bytes")
                }

                override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                    super.onClosed(webSocket, code, reason)
                    LogUtils.debugInfo("========================onClosed-->code:$code\treason$reason")
                    webSocketUtils.endHeart()
//
                }

                override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                    super.onClosing(webSocket, code, reason)
                    LogUtils.debugInfo("========================onClosing-->code:$code\treason$reason")
                    webSocketUtils.endHeart()
//                    webSocketUtils.reConnect()
                }

                override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                    super.onFailure(webSocket, t, response)
                    LogUtils.debugInfo("========================onFailure-->throwable:$t")
//                    webSocketUtils.reConnect()
                    webSocketUtils.endHeart()
                }
            })
        webSocketUtils.startHeart("", 10000)
    }


    override fun initData() {
        super.initData()
        initRightMenu()
        /** 接收消息订阅-单只训放成功 */
        eventViewModel.singleTrainingSuccess.observeInFragment(this) { it ->
            if (it) {
                mViewModel.isShowShare.set(false)
                mViewModel.isShowSingleTraining.set(true)
            }
        }

        /** 接收消息订阅-结束训放成功 */
        eventViewModel.stopTrainingSuccess.observeInFragment(this) { it ->
            if (it) {
                mViewModel.isShowShare.set(true)
                mViewModel.isShowSingleTraining.set(false)
            }
        }

        eventViewModel.getLonLatFailed.observeInFragment(this) {
            if (it) {
                if (intentType == 1) {
                    nav().navigateUp()
                } else {
                    nav().popBackStack(R.id.fragment_add_training, true)
                }
            }
        }
    }

    private fun initRightMenu() {
        if (trainingType == 1 && trainingStatus == 2) {
            mViewModel.isShowShare.set(false)
            mViewModel.isShowSingleTraining.set(true)
        } else {
            mViewModel.isShowShare.set(true)
            mViewModel.isShowSingleTraining.set(false)
        }
    }

    @SuppressLint("SimpleDateFormat")
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvTrainingDetailShare,
            mDatabind.tvTrainingDetailSingleTraining
        ) {
            when (it) {
                mDatabind.tvTrainingDetailShare -> {
                    try {
                        val sdf = SimpleDateFormat("yyyy-MM-dd")
                        val dateFormatString = sdf.format(Date(System.currentTimeMillis()))
                        val bmp = BitmapFactory.decodeResource(resources, R.mipmap.app_icon_)
                        WxShareUtils.shareWeb(
                            context,
                            Constant.WX_APP_ID,
                            Constant.SHARE_URL + "/training?t=$mId",
                            getString(R.string.Pigeon_little_treasure_pigeon_flying),
                            "" + dateFormatString,
                            bmp
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                        LogUtils.debugInfo(getString(R.string.get_training_info_fail))
                    }
                }

                mDatabind.tvTrainingDetailSingleTraining -> {
                    nav().navigateAction(R.id.action_to_single_training, Bundle().apply {
                        putString("trainingId", mId.toString())
                    })
                }
            }
        }
    }

    private fun initViewPager(id: Int) {
        val tabTitles = arrayListOf(getString(R.string.base_info), getString(R.string.training_result), getString(R.string.training_map))
        val fragmentList = ArrayList<Fragment>()
        fragmentList.add(
            FragmentTrainingInfo.newInstance(
                id,
                trainingStatus,
                trainingType,
                intentType
            )
        )
        fragmentList.add(FragmentTrainingResult.newInstance(id, result))
        fragmentList.add(FragmentTrainingFlyMap.newInstance(id, trainingStatus))
        mDatabind.viewPager.adapter = context?.let { MyPagerAdapter(childFragmentManager, it, fragmentList, tabTitles) }
        mDatabind.viewPager.offscreenPageLimit = 3
        mDatabind.tabLayout.setupWithViewPager(mDatabind.viewPager)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        webSocketUtils.cancel()
    }
}